package com.zzj.二维码; /**
 * @author: zzj
 * @date: 2018/01/05
 * Time: 16:41
 */
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;

public class QrCodeTool {
    public static Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
    @Test
    public void test1() {
        String filePath = "d:/qr_png.jpg";
        String str = "";
        /*
        for (int i = 0; i < 2685; i++) {
            str += 1;
        }
        */

        for (int i = 0; i < 635; i++) {
            str += "赵";
        }

       // encode(str, filePath);
        decode("d:\\01.jpg");
    }

    /**
     * qrcode 编码
     * @param conent
     * @param filePath  d:/qr_png.jpg
     */
    public static void encode(String conent, String filePath) {
        Charset charset = Charset.forName("UTF-8");
        CharsetEncoder encoder = charset.newEncoder();
        byte[] b = null;
        try { // Convert a string to ISO-8859-1 bytes in a ByteBuffer
            ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(conent));
            b = bbuf.array();
        } catch (CharacterCodingException e) {
            logger.error(e.getMessage(),e);
        }
        String data = "";
        try {
            data = new String(b, "iso8859-1");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(),e);
        } // get a byte matrix for the data
        BitMatrix matrix = null;
        int h = 900;
        int w = 800;
        com.google.zxing.Writer writer = new QRCodeWriter();
        try {
            matrix = writer.encode(data,
                    com.google.zxing.BarcodeFormat.QR_CODE, w, h);
        } catch (com.google.zxing.WriterException e) {
            logger.error(e.getMessage(),e);
        }
        File file = new File(filePath);
        try {
            MatrixToImageWriter.writeToFile(matrix, "PNG", file);
            logger.info("qrcode printing to " + file.getAbsolutePath());
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * qrcode解码，为空时，返回null
     * @param file
     * @return
     */
    public static String decode(String file) {
        try {
            Result result = null;
            BufferedImage image = null;
            image = ImageIO.read(new File(file));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            result = new MultiFormatReader().decode(bitmap, hints);
            String rtn = result.getText();
            return rtn;
        } catch (Exception ex) {
            logger.error(ex.getMessage(),ex);
            return null;
        }
    }
}